package 笔试;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class 三数之和 {
    public List<List<Integer>> threeSum(int[] nums) {
        int n = nums.length;
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        if(n < 3) {
            return res;
        }
        for(int first = 0; first < n; first++) {
            if(nums[first] > 0) {
                break;
            }
            if(first > 0 && nums[first] == nums[first-1]) {
                continue;
            }
            int third = n-1;
            int target = -nums[first];
            for(int second = first+1; second < n; second++) {
                if(second > first+1 && nums[second] == nums[second-1]) {
                    continue;
                }
                while(second < third && nums[third] + nums[second] > target) {
                    third--;
                }
                if(second == third) {
                    break;
                }
                if(nums[second] + nums[third] == target) {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[first]);
                    list.add(nums[second]);
                    list.add(nums[third]);
                    res.add(list);
                }
            }
        }
        return res;
    }
}
